package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.entity.Ossproperites;
import com.itheima.jsonresult.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Autowired
    private Ossproperites ossproperites;

    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossproperites.getEndpoint(), ossproperites.getAccessKey(), ossproperites.getSecret());
        try {
            ossClient.putObject(ossproperites.getBucketName(), fileName, new ByteArrayInputStream(file.getBytes()));
        } catch (Exception oe) {
            log.error("上传文件异常");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        // http://oss-cn-hangzhou.aliyuncs.com/a.jpg
        // https://linying-reggie.oss-cn-hangzhou.aliyuncs.com/1525189943-38523.png
        return new JsonResult(1, "上传成功", ossproperites.getUrl() + "/" + fileName,null);
    }
}
